package admin

import (
	"beego_starter/controllers"
	"beego_starter/models"

	"github.com/oldfeel/ofutils"
)

// 用户
type User struct {
	controllers.BaseController
}

// @Title 登录
// @Description 用户登录
// @Param name query string true "用户名"
// @Param password query string true "密码"
// @Success 200 {object} models.User
// @router /login [get]
func (c *User) Login() {
	name := c.GetString("name")
	password := c.GetString("password")

	var m models.User

	o.QueryTable(m).Filter("Name", name).Filter("Password", ofutils.MD5(password)).One(&m)
	if m.Id == 0 {
		c.Fail(1, "账号或密码错误")
		return
	}
	if name != "admin" {
		c.Fail(2, "请用管理员账号登录")
		return
	}
	m.Token = ofutils.RandString(32)
	o.Update(&m, "Token")
	m.Password = ""
	c.Success(m)
}

func (c *User) Info() {
	if !c.CheckLogin() {
		return
	}
	c.U.Password = ""
	c.U.Token = ""
	c.Success(c.U)
}

func (c *User) List() {
	page, _ := c.GetInt("page")
	pageSize, _ := c.GetInt("pageSize")

	var list []models.User
	qs := o.QueryTable("User").Offset(page * pageSize).Limit(pageSize).OrderBy("-CreateTime")
	qs.All(&list)
	for i, _ := range list {
		list[i].Password = ""
		list[i].Token = ""
	}
	c.Page(list, qs)
}
